__author__ = "Massimo Bonvicini"
__date__ = "$Jun 25, 2009 12:08:38 PM$"

from Errors import NotInGameError
from Errors import NotInHandError
from ManaPool import ManaPool
import logging
import copy
from random import shuffle
import toolbox
#from Errors import NotEnoughManaError
#from Card import Land

log = logging.getLogger(__name__)

class Player(object):
    showList = ['id', 'name', 'life', 'manaPool']
    
    def __init__(self, name):
        self.id = toolbox.genID(name)
        self.name = name
        self.life = 20
        self.library = None
        self.graveyard = []
        self.hand = []
        self.decks = {}
        self.tapped = []
        self.in_play = []
        self.land_played = False
        self.manaPool = ManaPool()
        
    def __repr__(self):
        return toolbox.str_impl(self, self.showList)
        
    def __str__(self):
        return repr(self)
        
    def addDeck(self, deck):
        self.decks[deck.name] = deck

    def selectDeck(self, name):
        self.library = self.decks[name]
        self.library.setOwner(self)

    def drawHand(self):
        if self.library:
            shuffle(self.library)
            self.hand = self.library[:7]
            self.library = self.library[7:]

    def draw(self, count):
        if self.library:
            for i in xrange(count):
                self.hand.append(self.library.pop())

    def untap(self):
        for card in self.tapped:
            card.untap()
        self.tapped = []

    def tap(self, card):
        if card in self.in_play:
            card.tap()
            self.tapped.append(card)
        else:
            raise NotInGameError(card)

    def play(self, card):
        if card in self.hand:
            if card.on_play():
                self.in_play.append(self.hand.pop(self.hand.index(card)))
        else:
            raise NotInHandError(card)

    def pay(self, card):
        '''
        Paga un costo in mana per una spell generica
        '''
        state = copy.deepcopy(self.manaPool)
        print self.manaPool, sum(self.manaPool.values())
        if not self.manaPool.pay(card):
            self.manaPool = copy.deepcopy(state)
            return False
        else:
            print self.manaPool, sum(self.manaPool.values())
            return True